package com.rui.study.commons.support;

import com.rui.study.commons.model.BizException;
import com.rui.study.commons.model.StatusCode;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.util.List;


@Aspect
@Component
public class ValidationAspect {

    private static final Logger LOGGER = LoggerFactory.getLogger(ValidationAspect.class);



    @Before("execution(* com.rui.study..*.controller.*Controller.*(..)) && args(.., bindingResult)")
    public void validateAccount(BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            List<FieldError> errors = bindingResult.getFieldErrors();
         StringBuffer errorMsg = new StringBuffer("非法参数：");
            for (int i = 0; i < errors.size(); i++) {
                FieldError error = errors.get(i);
                String fieldname = error.getField();
                String message = error.getDefaultMessage();
                errorMsg.append(String.format("%s%s;", fieldname, message));
            }
            errorMsg.deleteCharAt(errorMsg.length() - 1);
            LOGGER.info(errorMsg.toString());
            throw new BizException(StatusCode.ILLEGAL_PARAMETER, errorMsg.toString());
        }
    }

}
